import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class Student{
    public int id;
    public String name;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
public class JDBCinsertDemo {
    static List<Student> list = new ArrayList<>();
    public static void main(String[] args) throws SQLException {
        //创建数据源
        DataSource dataSource = new MysqlDataSource();//向上转型
        //向下转型
        //127.0.0.1->特殊ip  环回ip  相当于Java中的this
        //3306 端口号
        //useSSL=false -> 关闭加密功能
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/exam?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("284013");

        //和数据库建立连接
        Connection connection =dataSource.getConnection();

        Scanner scanner = new Scanner(System.in);
        //方法1，直接写sql语句
        //String sql = "insert into student values(1,'张三')";


        //方法3 构造Sql语句  ?->占位符
        // 容易记混
//         String sql = "insert into student values("+ id +", '" + name + "')";
        /*String sql = "insert into student values(?,?)";
        System.out.println("请输入学号：");
        int id = scanner.nextInt();
        System.out.println("请输入姓名：");
        String name = scanner.next();*/

        String sql = scanner.nextLine();

        PreparedStatement statement = connection.prepareStatement(sql);

/*        ResultSet resultSet = null;

        try {
            resultSet = statement.executeQuery();
            while(resultSet.next()){
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                list.add(new Student(id,name));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        for (Student student: list) {
            System.out.println(student.toString());
        }*/

        //占位符下标从0开始
        /*statement.setInt(1,id);
        statement.setString(2,name);*/
        int ret = statement.executeUpdate();
        System.out.println("sql: " + statement);//输出sql语句的信息
        System.out.println("ret = "+ret);
        statement.close();
        connection.close();
    }
}